package com.kuiandjie.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import com.kuiandjie.entity.Files;
import com.kuiandjie.util.DBHelp;
import com.kuiandjie.util.RowMapper;

public class FileDao {
	DBHelp<Files> db = new DBHelp<Files>();
	
	private class FileRowMapper implements RowMapper<Files>{

		@Override
		public Files mapperRow(ResultSet rs) throws SQLException {
			Files f = new Files();
			f.setId(rs.getInt("id"));
			f.setCreateTime(rs.getString("createtime"));
			f.setEmployeeId(rs.getInt("employeeid"));
			f.setFileName(rs.getString("filename"));
			f.setFileSize(rs.getLong("filesize"));
			f.setFileTypeId(rs.getInt("fileTypeid"));
			f.setName(rs.getString("name"));
			f.setEmpName(rs.getString("empname"));
			f.setType(rs.getString("type"));
			return f;
		}
		
	}

	public List<Files> findAllByFileTypeId(String folderid) {
		String sql = "SELECT t_file.id as id,t_file.name as name,filename,filesize,createtime,fileTypeid,employeeid,t_employee.name AS empname,type FROM t_file LEFT JOIN t_employee ON t_file.employeeid = t_employee.id WHERE fileTypeid = ? ORDER BY createtime DESC";
		return  db.executeQueryForList(sql, new FileRowMapper(), folderid);
	}

	public void addFile(Files f) {
		String sql = "INSERT INTO t_file(name,filename,createtime,filesize,employeeid,fileTypeid,type) VALUES(?,?,?,?,?,?,?)";
		db.executeSQL(sql, f.getName(),f.getFileName(),f.getCreateTime(),f.getFileSize(),f.getEmployeeId(),f.getFileTypeId(),f.getType());
	}

	public Files findByIdAndEmpId(String fileid, int id) {
		String sql = "SELECT id,name,name AS empname,filename,filesize,fileTypeid,employeeid,createtime,type FROM t_file WHERE id = ? AND employeeid = ?";
		return db.executeQueryForObject(sql, new FileRowMapper(), fileid,id);
	}

	public void delById(String fileid) {
		String sql = "DELETE FROM t_file WHERE id = ?";
		db.executeSQL(sql, fileid);
		
	}

	public Files findNameByFileName(String filename) {
		String sql = "SELECT id,name,name AS empname,filename,filesize,fileTypeid,employeeid,createtime,type FROM t_file WHERE filename = ?";
		return db.executeQueryForObject(sql, new FileRowMapper(), filename);
	}

}
